package com.newsappserver.userservice.controller;

import com.newsappserver.userservice.defines.StatusConstant;
import com.newsappserver.userservice.dto.request.UserCreateRequest;
import com.newsappserver.userservice.dto.request.UserUpdateRequest;
import com.newsappserver.userservice.dto.response.ApiResponse;
import com.newsappserver.userservice.dto.response.IntrospectResponse;
import com.newsappserver.userservice.dto.response.UserResponse;
import com.newsappserver.userservice.service.UserService;
import jakarta.validation.Valid;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
@RestController
@RequestMapping("/api/user")
public class UserController {
    UserService userService;

    //映射了两个路径。
    @PostMapping({"/signup", "/register"}) // POST signup or register
    private ApiResponse<UserResponse> userCreate(
            @RequestBody @Valid UserCreateRequest userCreateRequest
    ) {
        ApiResponse<UserResponse> apiResponse = new ApiResponse<>();
        log.info("USER-SERVICE: {}", userService);

        apiResponse.setMessage(StatusConstant.SUCCESS);
        apiResponse.setData(userService.userCreate(userCreateRequest));

        return apiResponse;
    }

    // 1. 去database client的userdb的user_entity_roles表，加入admin的角色为ADMIN
    // 2. 然后使用admin登录login接口获得token
    // 3. 使用token获得所有帐号
    /*
    GET http://localhost:8080/api/user
    Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiIxNjkwNTQ0NTUwQHFxLmNvbSIsInN1YiI6ImFkbWluIiwiZXhwIjoxNzQ4ODU4ODQ1LCJpYXQiOjE3NDYyNjY4NDUsInNjb3BlIjoiQURNSU4ifQ.m6Pv-km4U-NDSTe8MIMRHfQ2pMSllslfR9goxqMlOq7Hw0KHbw9LC6cXHd_j1E9hDpHi8kAVCDCYHzLLziVoBg
     */
    @GetMapping // GET
    private ApiResponse<List<UserResponse>> getAllUsers() {
        var auth = SecurityContextHolder.getContext().getAuthentication();

        log.info("USER-SERVICE: {}", userService);
        log.info("USER-SERVICE: {}", auth.getName());

        auth.getAuthorities().forEach(grantedAuthority -> {
            log.info("USER-SERVICE: {}", grantedAuthority.getAuthority());
        });

        return ApiResponse.<List<UserResponse>>builder()
                .code(HttpStatus.OK.value())
                .message(StatusConstant.SUCCESS)
                .data(userService.getAllUsers())
                .build();
    }

    /* vscode rest client 测试
    GET http://localhost:8080/api/user/2
    Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiIxNjkwNTQ0NTUwQHFxLmNvbSIsInN1YiI6InJvb3QiLCJleHAiOjE3NDg4NTY5MzUsImlhdCI6MTc0NjI2NDkzNSwic2NvcGUiOiJVU0VSIn0.fbDhfAH0s06CmEwkhhrWawYv4CAlUY5FWM-XRvI2BeAOLdkKnH3hVbkfk_Wup8YlQPNCo3Nwx5HHB_pB3FaHFw
    * */
    @GetMapping("/{userId}") // GET /1
    private ApiResponse<UserResponse> getUser(@PathVariable("userId") Long userId) {
        return ApiResponse.<UserResponse>builder()
                .code(HttpStatus.OK.value())
                .message(StatusConstant.SUCCESS)
                .data(userService.getUserById(userId))
                .build();
    }

    /* vscode rest client 测试:
    GET http://localhost:8080/api/user/my-info
    Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiIxNjkwNTQ0NTUwQHFxLmNvbSIsInN1YiI6InJvb3QiLCJleHAiOjE3NDg4NTc4MzEsImlhdCI6MTc0NjI2NTgzMSwic2NvcGUiOiJVU0VSIn0.yN3G9TVAifj2wtP_PhcxrunLHQv2VfK3MNEdomRxifUNMTfHY-M2vGC5jwA4iepqKi_D8AuuTwIeytJJ-U0YFA
     */
    @GetMapping("/my-info") // GET my own info
    private ApiResponse<UserResponse> getMyInfo() {
        return ApiResponse.<UserResponse>builder()
                .code(HttpStatus.OK.value())
                .message(StatusConstant.SUCCESS)
                .data(userService.getUserOwnerInfo())
                .build();
    }

    /*
    PUT http://localhost:8080/api/user/3
    Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiIxNjkwNTQ0NTUwQHFxLmNvbSIsInN1YiI6InJvb3QiLCJleHAiOjE3NDg4NTc4MzEsImlhdCI6MTc0NjI2NTgzMSwic2NvcGUiOiJVU0VSIn0.yN3G9TVAifj2wtP_PhcxrunLHQv2VfK3MNEdomRxifUNMTfHY-M2vGC5jwA4iepqKi_D8AuuTwIeytJJ-U0YFA
    Content-Type: application/json

    {
        "name": "damn",
        "email": "damn@damn.org",
        "password": "88888888"
    }
     */
    @PutMapping("/{userId}") // PUT 更新账户
    private ApiResponse<UserResponse> updateUser(
            @PathVariable("userId") Long userId,
            @RequestBody UserUpdateRequest userUpdateRequest) {
        return ApiResponse.<UserResponse>builder()
                .code(HttpStatus.OK.value())
                .message(StatusConstant.SUCCESS)
                .data(userService.updateUser(userUpdateRequest, userId))
                .build();
    }

    /*
    DELETE  http://localhost:8080/api/user/2
    Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiIxNjkwNTQ0NTUwQHFxLmNvbSIsInN1YiI6InJvb3QiLCJleHAiOjE3NDg4NTc4MzEsImlhdCI6MTc0NjI2NTgzMSwic2NvcGUiOiJVU0VSIn0.yN3G9TVAifj2wtP_PhcxrunLHQv2VfK3MNEdomRxifUNMTfHY-M2vGC5jwA4iepqKi_D8AuuTwIeytJJ-U0YFA
     */
    @DeleteMapping("/{userId}")
    private ApiResponse<IntrospectResponse> deleteUser(@PathVariable("userId") Long userId) {
        var result = userService.deleteUserById(userId);

        HttpStatus httpStatus = result.isValid() ? HttpStatus.OK : HttpStatus.BAD_REQUEST;

        String message = result.isValid() ? StatusConstant.SUCCESS : StatusConstant.FAILED;

        return ApiResponse.<IntrospectResponse>builder()
                .code(httpStatus.value())
                .message(message)
                .data(result)
                .build();
    }

}
